#!/usr/bin/env python3

import inquirer as inq
from inquirer.themes import GreenPassion
import nfmov
from typing import List
import os, sys
import downloader
from downloader_ui import DownloaderUI, TaskMan


def prompt(questions):
    answers = inq.prompt(questions, theme=GreenPassion())
    if not answers:
        sys.exit(0)
    return answers


def get_name():
    answers = prompt(
        [inq.Text(name='name', message='要检索的电影名(输入 "quit" 将退出程序)')])
    return answers['name'].strip()


def select_query_items(items: List[nfmov.QueryItem]) -> nfmov.QueryItem:
    choices = []
    for i, v in enumerate(items):
        title = '{} | 导演: {} | 主演: {}'.format(v.name, '/'.join(v.directors)
                                              or '', '/'.join(v.actors) or '')
        choices.append((title, i))

    questions = [
        inq.List(name='item', message='选择片子', choices=choices, default=0)
    ]
    answers = prompt(questions)
    return items[answers['item']]


def select_source(sources: List[nfmov.Source]) -> nfmov.Source:
    choices = [(s.name, i) for i, s in enumerate(sources)]
    questions = [
        inq.List(name='item', message='选择片源', choices=choices, default=0)
    ]
    answers = prompt(questions)
    return sources[answers['item']]


def select_video(videos: List[nfmov.Video]) -> nfmov.Video:
    choices = []
    if len(videos) > 0:
        choices.append(('全给老子下载下来', -1))
    choices.extend([(s.name, i) for i, s in enumerate(videos)])
    questions = [
        inq.List(name='item', message='选择剧集', choices=choices, default=-1)
    ]
    answers = prompt(questions)
    i = answers['item']
    if i == -1:
        return videos
    return videos[i]


def select_video_action(video: nfmov.Video, video_name: str):
    choices = [('播放', play), ('下载', download)]
    questions = [inq.List(name='action', choices=choices)]
    answers = prompt(questions)
    return answers['action'](video, video_name)


def download(video: nfmov.Video, video_name: str, dui_key=None):
    dui = None
    if dui_key is None:
        dui = DownloaderUI()
        dui_key = dui.key
    res = downloader.download(video.url, video_name, video.name,
                              TaskMan(dui_key))
    myprint('从 {} 下载文件 {}'.format(video.url, f'{res} 完成' if res else '失败'))
    if dui:
        dui.join()


def download_all(videos: List[nfmov.Video], video_name: str):
    dui = DownloaderUI()
    from multiprocessing import Pool
    p = Pool(3)
    for v in videos:
        if v.url:
            p.apply_async(download, args=(v, video_name, dui.key))
    p.close()
    p.join()
    dui.join()


def play(video: nfmov.Video, video_name: str):
    myprint(f'播放: [{video_name}-{video.name}] -> {video.url}')
    os.system(
        f'open -a /System/Applications/QuickTime\ Player.app "{video.url}"')


def myprint(log):
    print(log)


def logic():
    # 获取名字
    name = get_name()
    if not name:
        return
    if name == 'quit':
        sys.exit(0)
    # 检索
    query_items = nfmov.query(name)
    if not query_items:
        myprint(f'找不到和 "{name}" 相关的视频')
        return
    # 选择检索结果
    query_item = select_query_items(query_items)
    # 选择视频源
    if not query_item.sources:
        myprint('没有可播放资源')
        return
    source = select_source(query_item.sources)
    # 选择剧集
    if not source.videos:
        myprint('没有可播放剧集')
        return
    video = select_video(source.videos)
    # 选择对剧集执行的操作
    # 一组视频就执行下载
    video_name = query_item.name
    if isinstance(video, list):
        return download_all(video, video_name)
    # 单个视频就选择操作
    if not video.url:
        myprint('找不到视频链接')
        return
    select_video_action(video, video_name)


if __name__ == '__main__':
    while True:
        logic()
